//
//  MPCNavigationBar.m
//  Pods
//
//  Created by 龙鹏飞 on 2017/9/15.
//
//

#import "MPCNavigationBar.h"
#import "Masonry.h"
#import "MPToolsHeader.h"

#define MPCNavigationBarTitleFont [UIFont YXRegularFontOdSize:18]


@interface MPCNavigationBar ()

@property (nonatomic, weak) UIViewController *viewController;
@property (nonatomic, strong) NSString *leftBarButtonImageName;
@property (nonatomic, strong) NSString *leftBarButtonHighlightedImageName;
@property (nonatomic, strong) NSString *rightBarButtonImageName;
@property (nonatomic, strong) NSString *rightBarButtonHighlightedImageName;
@property (nonatomic, assign) BOOL needStatusBar;

@property (nonatomic, strong, readwrite) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *leftBarButton;
@property (nonatomic, strong) UIButton *rightBarButton;
@property (nonatomic, strong) UIView *bottomLine;
@property (nonatomic, strong, readwrite) UIImageView *backgroundImageView;

@property (nonatomic, assign) BOOL finishinitializing; //是否初始化完成
@property (nonatomic, strong) UIVisualEffectView *effectView;

@end

@implementation MPCNavigationBar

#pragma mark - init / config

- (instancetype)initNavigationBarWithViewController:(UIViewController *)viewController
                                      needStatusBar:(BOOL)needStatusBar
{
    return [self initNavigationBarWithViewController:viewController title:nil leftBarButtonImageName:nil leftBarButtonHighlightedImageName:nil rightBarButtonImageName:nil rightBarButtonHighlightedImageName:nil needStatusBar:needStatusBar];
}

- (instancetype)initNavigationBarWithViewController:(UIViewController *)viewController
                                              title:(NSString *)title
                             leftBarButtonImageName:(NSString *)leftBarButtonImageName
                                      needStatusBar:(BOOL)needStatusBar
{
    return [self initNavigationBarWithViewController:viewController title:title leftBarButtonImageName:leftBarButtonImageName leftBarButtonHighlightedImageName:nil rightBarButtonImageName:nil rightBarButtonHighlightedImageName:nil needStatusBar:needStatusBar];
}

- (instancetype)initNavigationBarWithViewController:(UIViewController *)viewController
                                              title:(NSString *)title
                             leftBarButtonImageName:(NSString *)leftBarButtonImageName
                  leftBarButtonHighlightedImageName:(NSString *)leftBarButtonHighlightedImageName
                                      needStatusBar:(BOOL)needStatusBar
{
    return [self initNavigationBarWithViewController:viewController title:title leftBarButtonImageName:leftBarButtonImageName leftBarButtonHighlightedImageName:leftBarButtonHighlightedImageName rightBarButtonImageName:nil rightBarButtonHighlightedImageName:nil needStatusBar:needStatusBar];
}

- (instancetype)initNavigationBarWithViewController:(UIViewController *)viewController
                                              title:(NSString *)title
                             leftBarButtonImageName:(NSString *)leftBarButtonImageName
                  leftBarButtonHighlightedImageName:(NSString *)leftBarButtonHighlightedImageName
                            rightBarButtonImageName:(NSString *)rightBarButtonImageName
                  rightBarButtonHighlightedImageName:(NSString *)rightBarButtonHighlightedImageName
                                      needStatusBar:(BOOL)needStatusBar
{
    if (self = [super init])
    {
        NSAssert((viewController && [viewController isKindOfClass:[UIViewController class]]), @"viewController参数错误");
        self.viewController = viewController;
        self.title = title;
        self.leftBarButtonImageName = leftBarButtonImageName;
        self.rightBarButtonImageName = rightBarButtonImageName;
        self.needStatusBar = needStatusBar;
        [self initialize];
        self.finishinitializing = YES;
    }
    
    return  self;
}

- (void)initialize
{
    self.backgroundColor = [UIColor whiteColor];
    
    if (self.needStatusBar)
    {
        self.frame = CGRectMake(0, 0, SCREEN_SIZE.width, 64);
    }
    else
    {
        self.frame = CGRectMake(0, 0, SCREEN_SIZE.width, 44);
    }
    
    [self addSubview:self.contentView];
    self.contentView.frame = self.bounds;
    
    if (self.viewController && [self.viewController isKindOfClass:[UIViewController class]])
    {
        [self.viewController.view insertSubview:self atIndex:999];
    }
    
    if (MPT_Str_Is_Valid(self.title))
    {
        self.titleLabel.text = self.title;
        [self.contentView addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.contentView.mas_centerX);
            make.centerY.equalTo(self.contentView.mas_centerY).offset(self.needStatusBar?10:0);
        }];
        self.titleLabel.font = MPCNavigationBarTitleFont;
    }
    
    if (MPT_Str_Is_Valid(self.leftBarButtonImageName))
    {
        UIImage *image = [UIImage imageNamed:self.leftBarButtonImageName];
        UIImage *highlight = [UIImage imageNamed:MPT_Str_Is_Valid(self.leftBarButtonHighlightedImageName)?self.leftBarButtonHighlightedImageName:@""];
        if (image)
        {
            if (highlight)
            {
                [self.leftBarButton setImage:image forState:UIControlStateNormal];
                [self.leftBarButton setImage:highlight forState:UIControlStateHighlighted];
            }
            else
            {
                [self.leftBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            }
            [self.contentView addSubview:self.leftBarButton];
            [self.leftBarButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.and.bottom.equalTo(self.contentView);
                make.top.equalTo(self.contentView.mas_top).offset(self.needStatusBar?20:0);
                make.width.mas_equalTo(44);
            }];
        }
    }
    
    if (MPT_Str_Is_Valid(self.rightBarButtonImageName))
    {
        UIImage *image = [UIImage imageNamed:self.rightBarButtonImageName];
        UIImage *highlight = [UIImage imageNamed:MPT_Str_Is_Valid(self.rightBarButtonHighlightedImageName)?self.rightBarButtonHighlightedImageName:@""];
        if (image)
        {
            if (highlight)
            {
                [self.rightBarButton setImage:image forState:UIControlStateNormal];
                [self.rightBarButton setImage:highlight forState:UIControlStateHighlighted];
            }
            else
            {
                [self.rightBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            }
            [self.contentView addSubview:self.rightBarButton];
            [self.rightBarButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.trailing.and.and.bottom.equalTo(self.contentView);
                make.top.equalTo(self.contentView.mas_top).offset(self.needStatusBar?20:0);
                make.width.mas_equalTo(44);
            }];
        }
    }
    
    [self.contentView addSubview:self.bottomLine];
    [self.bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.trailing.and.bottom.equalTo(self.contentView);
        make.height.mas_equalTo(0.5);
    }];
}

- (void)setBottomLineHidden:(BOOL)hidden
{
    self.bottomLine.hidden = hidden;
}

- (void)setBarAlpha:(CGFloat)alpha
{
    if (self.backgroundImageView.superview)
    {
        self.backgroundImageView.alpha = alpha;
    }
    else
    {
        self.backgroundColor = [self.backgroundColor colorWithAlphaComponent:alpha];
    }
}

- (void)setLeftBarButtonImageName:(NSString *)leftBarButtonImageName leftBarButtonHighlightedImageName:(NSString *)leftBarButtonHighlightedImageName
{
    if (![self.contentView.subviews containsObject:self.leftBarButton])
    {
        [self.contentView addSubview:self.leftBarButton];
        [self.leftBarButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.and.bottom.equalTo(self.contentView);
            make.top.equalTo(self.contentView.mas_top).offset(self.needStatusBar?20:0);
            make.width.mas_equalTo(44);
        }];
    }
    UIImage *image = [UIImage imageNamed:leftBarButtonImageName];
    UIImage *highlight = [UIImage imageNamed:MPT_Str_Is_Valid(leftBarButtonHighlightedImageName)?leftBarButtonHighlightedImageName:@""];
    if (image)
    {
        if (highlight)
        {
            [self.rightBarButton setImage:image forState:UIControlStateNormal];
            [self.rightBarButton setImage:highlight forState:UIControlStateHighlighted];
        }
        else
        {
            [self.rightBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }
    }
}

- (void)setRightBarButtonImageName:(NSString *)rightBarButtonImageName rightBarButtonHighlightedImageName:(NSString *)rightBarButtonHighlightedImageName
{
    if (![self.contentView.subviews containsObject:self.rightBarButton])
    {
        [self.contentView addSubview:self.rightBarButton];
        [self.rightBarButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.and.and.bottom.equalTo(self.contentView);
            make.top.equalTo(self.contentView.mas_top).offset(self.needStatusBar?20:0);
            make.width.mas_equalTo(44);
        }];
    }
    UIImage *image = [UIImage imageNamed:rightBarButtonImageName];
    UIImage *highlight = [UIImage imageNamed:MPT_Str_Is_Valid(rightBarButtonHighlightedImageName)?rightBarButtonHighlightedImageName:@""];
    if (image)
    {
        if (highlight)
        {
            [self.rightBarButton setImage:image forState:UIControlStateNormal];
            [self.rightBarButton setImage:highlight forState:UIControlStateHighlighted];
        }
        else
        {
            [self.rightBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }
    }
}

#pragma mark - actions

- (void)leftBarButtonAction:(UIButton *)button
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(leftBarButtonDidClicked:)])
    {
        [self.delegate leftBarButtonDidClicked:button];
    }
    else
    {
        if (self.viewController && [self.viewController isKindOfClass:[UIViewController class]])
        {
            if (self.viewController.navigationController &&
                self.viewController.navigationController.viewControllers.count > 1)
            {
                [self.viewController.navigationController popViewControllerAnimated:YES];
            }
        }
    }
}

- (void)rightBarButtonAction:(UIButton *)button
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(rightBarButtonDidClicked:)])
    {
        [self.delegate rightBarButtonDidClicked:button];
    }
}

#pragma mark - getters / setters

- (UIView *)contentView
{
    if (!_contentView)
    {
        _contentView = [UIView new];
        _contentView.backgroundColor = [UIColor clearColor];
    }
    return _contentView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        _titleLabel = [UILabel new];
        _titleLabel.textColor = MPT_RGBAllColor(0x24242C);
        _titleLabel.font = MPCNavigationBarTitleFont;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UIButton *)leftBarButton
{
    if (!_leftBarButton)
    {
        _leftBarButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_leftBarButton addTarget:self action:@selector(leftBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftBarButton;
}

- (UIButton *)rightBarButton
{
    if (!_rightBarButton)
    {
        _rightBarButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_rightBarButton addTarget:self action:@selector(rightBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBarButton;
}

- (UIView *)bottomLine
{
    if (!_bottomLine)
    {
        _bottomLine = [UIView new];
        _bottomLine.backgroundColor = [UIColor YXColorWithHexCode:@"#B2B2B2"];
    }
    return _bottomLine;
}

- (UIImageView *)backgroundImageView
{
    if (!_backgroundImageView)
    {
        _backgroundImageView = [UIImageView new];
        _backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
        _backgroundImageView.clipsToBounds = YES;
    }
    return _backgroundImageView;
}

- (UIVisualEffectView *)effectView
{
    if (!_effectView)
    {
        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    }
    return _effectView;
}

- (void)setTitle:(NSString *)title
{
    if (_title != title)
    {
        _title = title;
        
        if (self.finishinitializing)
        {
            if (![self.subviews containsObject:self.titleLabel])
            {
                [self.contentView addSubview:self.titleLabel];
                [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(self.mas_centerX);
                    make.centerY.equalTo(self.mas_centerY).offset(self.needStatusBar?10:0);
                }];
            }
            self.titleLabel.text = _title;
            self.titleLabel.font = MPCNavigationBarTitleFont;
        }
    }
}

- (void)setTitleView:(UIView *)titleView
{
    if (_titleView)
    {
        if ([self.subviews containsObject:_titleView])
        {
            [_titleView removeFromSuperview];
        }
    }
    [self.contentView addSubview:titleView];
    CGRect frame = titleView.bounds;
    if (self.needStatusBar)
    {
        frame.origin.x = (SCREEN_SIZE.width-CGRectGetWidth(frame))/2.0;
        frame.origin.y = 44 - CGRectGetHeight(frame)/2.0;
    }
    else
    {
        frame.origin.x = (SCREEN_SIZE.width-CGRectGetWidth(frame))/2.0;
        frame.origin.y = CGRectGetMidY(frame) - CGRectGetHeight(frame)/2.0;
    }
    _titleView = titleView;
    
}

- (void)setBackgroundImage:(UIImage *)backgroundImage
{
    if (_backgroundImage != backgroundImage)
    {
        if (![self.subviews containsObject:self.backgroundImageView])
        {
            [self insertSubview:self.backgroundImageView atIndex:0];
            self.backgroundImageView.frame = self.bounds;
            [super setBackgroundColor:[UIColor clearColor]];
        }
        
        _backgroundImage = backgroundImage;
        
        if (backgroundImage && [backgroundImage isKindOfClass:[UIImage class]])
        {
            self.backgroundImageView.image = _backgroundImage;
        }
        
        if (self.needBlur)
        {
            if (self.effectView.superview) {
                if (self.effectView.superview != self.backgroundImageView)
                {
                    [self.effectView removeFromSuperview];
                    [self.backgroundImageView addSubview:self.effectView];
                    self.effectView.frame = self.backgroundImageView.bounds;
                }
            }
            else
            {
                [self.backgroundImageView addSubview:self.effectView];
                self.effectView.frame = self.backgroundImageView.bounds;
            }
        }
        
    }
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    if (self.backgroundImageView.superview)
    {
        return;
    }
    else
    {
        [super setBackgroundColor:backgroundColor];
    }
}

- (void)setNeedBlur:(BOOL)needBlur
{
    if (_needBlur != needBlur)
    {
        _needBlur = needBlur;
        
        if (needBlur)
        {
            if ([self.subviews containsObject:self.backgroundImageView])
            {
                [self.backgroundImageView addSubview:self.effectView];
                self.effectView.frame = self.backgroundImageView.bounds;
            }
            else
            {
                [self insertSubview:self.effectView belowSubview:self.contentView];
                self.effectView.frame = self.bounds;
            }
        }
        else
        {
            if (self.effectView.superview)
            {
                [self.effectView removeFromSuperview];
            }
        }
    }
}

@end
